package com.itwxz.quartz.task;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.itwxz.common.config.WxzConfig;
import com.itwxz.common.constant.CacheConstants;
import com.itwxz.common.core.redis.RedisCache;
import com.itwxz.system.domain.po.Weather;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class EveryHourTask {

	private final RedisCache redisCache;
	private final WxzConfig wxzConfig;

	private static final String CITY_CODE = "440118";
	private static final String WEATHER_KEY = CacheConstants.WEATHER_KEY;

	@PostConstruct
	public void init() {
		getWeather(); // 启动时执行一次
	}

	/**
	 * 每小时更新一次实时天气
	 */
	public void getWeather() {
		String url = String.format(
				"https://restapi.amap.com/v3/weather/weatherInfo?key=%s&city=%s&extensions=base",
				wxzConfig.getAMapKey(), CITY_CODE
		);

		try {
			// 请求高德天气 API
			String result = HttpUtil.get(url);
			log.debug("高德天气接口返回原始数据: {}", result);

			JSONObject json = JSON.parseObject(result);
			if (json == null) {
				log.warn("天气接口返回空结果");
				redisCache.deleteObject(WEATHER_KEY);
				return;
			}

			// 校验接口返回状态
			if (!"1".equals(json.getString("status"))) {
				log.warn("天气接口调用失败: code={}, info={}",
						json.getString("infocode"), json.getString("info"));
				redisCache.deleteObject(WEATHER_KEY);
				return;
			}

			// 提取实时天气数据
			JSONObject live = json.getJSONArray("lives").getJSONObject(0);
			Weather weather = live.toJavaObject(Weather.class);

			// 打印关键字段日志
			log.info("更新天气成功: 城市={}, 天气={}, 温度={}℃, 湿度={}%",
					weather.getCity(), weather.getWeather(),
					weather.getTemperature(), weather.getHumidity());

			// 存入 Redis
			redisCache.setCacheObject(WEATHER_KEY, weather);

		} catch (Exception e) {
			log.error("获取天气接口异常", e);
			redisCache.deleteObject(WEATHER_KEY);
		}
	}
}